package com.linkq.ipinyin.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linkq.core.base.BaseService;
import com.linkq.ipinyin.dao.ExecutionPlanDao;
import com.linkq.ipinyin.mapper.CnCharacterMapper;
import com.linkq.ipinyin.mapper.ExecutionContentMapper;
import com.linkq.ipinyin.mapper.ExecutionPlanMapper;
import com.linkq.ipinyin.model.CnCharacter;
import com.linkq.ipinyin.model.ExecutionContent;
import com.linkq.ipinyin.model.ExecutionPlan;
import com.linkq.ipinyin.vo.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @FileName BcExecutionPlanService
 * @Description
 * @Author wangpeng
 * @date 2025-01-01
 **/

@Service
@Transactional
public class ExecutionPlanService extends BaseService<ExecutionPlanDao, ExecutionPlan> {

    @Autowired
    private ExecutionPlanMapper executionPlanMapper;
    @Autowired
    private ExecutionContentMapper executionContentMapper;
    @Autowired
    private CnCharacterMapper characterMapper;

    public ResultInfo getExecutePlan(ExecutionPlan executionPlan) {
        ExecutionPlan info = executionPlanMapper.selectById(executionPlan.getId());
        List<ExecutionContent> executionContentList = executionContentMapper.selectList(
                Wrappers.<ExecutionContent>lambdaQuery()
                        .eq(ExecutionContent::getExecutionPlanId, info.getId())
        );
        List<CnCharacter> characterList = characterMapper.selectList(
                Wrappers.<CnCharacter>lambdaQuery()
                        .in(CnCharacter::getId, executionContentList.stream().map(ExecutionContent::getCharacterId).collect(Collectors.toList()))
        );
        info.setCharacterList(characterList);
        return ResultInfo.success(info);
    }

    /**
     * 开始执行学习计划
     * @param executionPlan
     * @return
     */
    public ResultInfo startExecutePlan(ExecutionPlan executionPlan) {
        ExecutionPlan info = executionPlanMapper.selectById(executionPlan.getId());
        if (info.getStatus() != 0) {
            return ResultInfo.error("当前状态无法开始执行学习计划", -1);
        }
        info.setStatus(1);
        info.setExecuteStartTime(new Date());
        if (executionPlanMapper.updateById(info) > 0) {
            return ResultInfo.success("开始执行学习计划");
        }
        return ResultInfo.error("执行学习计划失败");
    }
}
